// 向页面注入JS
function injectCustomJs (jsPath) {
  jsPath = jsPath || './js/injectJs.js'
  var temp = document.createElement('script')
  temp.setAttribute('type', 'text/javascript')
  // 获得的地址类似：chrome-extension://ihcokhadfjfchaeagdoclpnjdiokfakg/js/inject.js
  temp.src = chrome.extension.getURL(jsPath)
  temp.onload = function () {
    // 放在页面不好看，执行完后移除掉
    this.parentNode.removeChild(this)
  }
  document.head.appendChild(temp)
}
injectCustomJs()
setTimeout(function () {
  var isdo = false
  $(function () {
    var $this = $('.dataFormInvest')
    var isCanuser = $('.dataFormInvest').length
    var formKey
    var youhave = $('.p_zc01').parent().find('h4').html() - 0
    if (isCanuser) {
      $('body,html').animate({
        scrollTop: $this.offset().top // 让body的scrollTop等于pos的top，就实现了滚动
      }, 0)
      formKey = parseInt($this.data('id'))
      var investNumber = 0
      // 单次 最多
      var maxNumber = $('#max_number' + formKey).val()
      investNumber = Math.min(maxNumber, youhave)
      // 好像是盘总数剩余
      // var surplus_number = $('#surplus_number' + formKey).val()
      // investNumber = Math.min(surplus_number, investNumber)
      // 必须大于最小
      var min_number = $('#min_number' + formKey).val()
      investNumber = Math.max(min_number, investNumber)
      if (investNumber > 0) {
        $('#number' + formKey).val(investNumber)
        setTimeout(function () {
          $this.trigger('submit')
        }, 100)
      } else {
        alert('已经没有余额了')
      }
    }
    chrome.runtime.onMessage.addListener(
      function (request, sender, sendResponse) {
        if (request.action == 'begin' && !isdo) {
          if (!isCanuser) {
            doReflash(request.ping)
          }
          sendResponse({state: 'ok', isStop: !!isCanuser})
          isdo = true
        }
      }
    )
    function doReflash (time) {
      console.log('window.location.reload')
      setTimeout(function () {
        window.location = window.location
      }, time)
    }
  })
}, 200)

chrome.runtime.sendMessage({action: 'onload'},
  function (sendResponse) {
  }
)
